﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Skyworth.CRM.Common
{
    /// <summary>
    /// A helper about cache object
    /// </summary>
    public class CacheHelper
    {
        private static readonly Cache _cacheObject;

        private CacheHelper() { }

        /// <summary>
        /// Static initializer should ensure we only have to look up the current cache instance once.        
        /// </summary>
        static CacheHelper()
        {
            HttpContext context = HttpContext.Current;
            _cacheObject = context != null ? context.Cache : HttpRuntime.Cache;
        }


        /// <summary>
        /// Insert an item into the cache
        /// </summary>
        /// <param name="key">The cache key</param>
        /// <param name="value">The cache value</param>
        /// <param name="expiredTime"></param>
        /// <param name="timeSpan">The interval since last access. If don't want to use it, set it to TimeSpan.Zero</param>
        public static void InsertCache(string key, object value, DateTime expiredTime, TimeSpan timeSpan)
        {
            //Cache cache = HttpContext.Current.Cache;
            //cache.Insert(key, value, null,expiredTime, timeSpan);
            _cacheObject.Insert(key, value, null, expiredTime, timeSpan);
        }

        /// <summary>
        /// Insert an item into the cache.
        /// </summary>
        /// <param name="key">The cache key</param>
        /// <param name="value">The cache value</param>
        /// <param name="dependencies">The specified cache dependency</param>
        public static void InsertCache(string key, object value, CacheDependency dependencies)
        {
            //Cache cache = HttpContext.Current.Cache;
            //cache.Insert(key, value, dependencies);
            _cacheObject.Insert(key, value, dependencies);
        }

        /// <summary>
        /// Remove cache item from cache.
        /// </summary>
        /// <param name="key">The cache key</param>
        public static void RemoveCache(string key)
        {
            //HttpContext.Current.Cache.Remove(key);
            _cacheObject.Remove(key);
        }

        /// <summary>
        /// Get the object associated with the key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The cache key</param>
        /// <returns></returns>
        public static T GetObjectFromCache<T>(string key)
        {
            //Cache cache = HttpContext.Current.Cache;
            //return cache.Get(key) == null ? default(T) : (T)cache.Get(key);
            return _cacheObject.Get(key) == null ? default(T) : (T)_cacheObject.Get(key);

        }
    }
}
